package com.ssyc.gsk_teacher.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.activity.TeacherAddStudentActivity;
import com.ssyc.gsk_teacher.activity.TeacherEditTeamActivity;
import com.ssyc.gsk_teacher.bean.CommitResultInfo;
import com.ssyc.gsk_teacher.bean.NoTeamClassInfo;
import com.ssyc.gsk_teacher.bean.StudentInfo;
import com.ssyc.gsk_teacher.bean.TeamInfo;
import com.ssyc.gsk_teacher.bean.TeamPassData;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * 展示小组的列表适配器
 * Created by Administrator on 2018/6/26 0026.
 */

public class TeamRvAdapter extends BaseQuickAdapter<TeamInfo.TeamsinfoBean, BaseViewHolder> {

    public static final int UPDATAPAGEDATA = 0x220;
    //Activity对象
    private Activity activity;

    //上下文
    private Context context;

    private int[] res = {R.drawable.teacher_team1, R.drawable.teacher_team2, R.drawable.teacher_team3, R.drawable.teacher_team4, R.drawable.teacher_team5,
            R.drawable.teacher_team6, R.drawable.teacher_team7, R.drawable.teacher_team8, R.drawable.teacher_team9, R.drawable.teacher_team10,};

    //展示未分组的学生的PopUpWindow相关控件
    private View view;
    private RelativeLayout rlLoading;
    private ListView lv;
    private List<StudentInfo> noTeamDatas;
    private StudentLvAdapter lvAdapter;
    private PopupWindow window;
    private Button btAddNewStudent;

    //展示小组成员的数据
    private List<StudentInfo> teamStudents;

    //需要传递的小组的数据对象
    private TeamPassData teamPassData;

    //数据源
    private List<TeamInfo.TeamsinfoBean> data;

    public TeamRvAdapter(Activity activity, Context context, int layoutResId, @Nullable List<TeamInfo.TeamsinfoBean> data) {
        super(layoutResId, data);
        this.context = context;
        this.activity = activity;
        this.data = data;
    }

    /**
     * 初始化封装小组各信息的对象
     */
    private void initPassTeamData() {
        teamPassData = new TeamPassData();
        List<String> teamNames = new ArrayList<>();
        List<String> teamSlogans = new ArrayList<>();
        List<String> teamAims = new ArrayList<>();
        List<String> teamMusics = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            teamNames.add(data.get(i).getName());
            teamSlogans.add(data.get(i).getSlogan());
            teamAims.add(data.get(i).getAim());
            teamMusics.add(data.get(i).getMusic());
        }
        teamPassData.teamNames = teamNames;
        teamPassData.teamSlogans = teamSlogans;
        teamPassData.teamAims = teamAims;
        teamPassData.teamMusics = teamMusics;
    }

    @Override
    protected void convert(BaseViewHolder helper, TeamInfo.TeamsinfoBean item) {

        //包含小组头像和姓名的线性布局,点击后跳转到标记
        LinearLayout llTeam = helper.getView(R.id.ll_team);
        llTeam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //初始化封装小组各信息的对象
                initPassTeamData();
                //跳转到编辑小组的界面
                Intent intent = new Intent(context, TeacherEditTeamActivity.class);
                intent.putExtra("teaminfo", item);
                //携带小组对象包含的名称,口号,目标,音乐等信息
                intent.putExtra("teampassdata", teamPassData);
                context.startActivity(intent);
            }
        });


        //小组头像
        CircleImageView ivTeam = helper.getView(R.id.iv_team_img);
        ivTeam.setImageResource(res[item.getIcon() - 1]);

        //小组姓名
        TextView tvTeamName = helper.getView(R.id.tv_team_name);
        if (TextUtils.isEmpty(item.getName())) {
            tvTeamName.setText("暂无");
        } else {
            tvTeamName.setText(item.getName());
        }

        //展示小组成员的GridView
        GridView mGv = helper.getView(R.id.mgv);

        //每个小组默认有四个成员
        List<StudentInfo> studentInfos = new ArrayList<>();

        //当前小组携带的小组学生成员信息,有可能有也有可能没有
        teamStudents = item.getStudentsinfo();
        if (null != teamStudents && teamStudents.size() != 0) {
            //先创建四个空的成员小组,这里注意给每个添加的成员配置classnum和teamnum
            for (int i = 0; i < 4; i++) {
                StudentInfo info = new StudentInfo();
                studentInfos.add(info);
                info.setClassnum(item.getClassnum());
                info.setTeamnum(item.getTeamnum());
                info.setRole((i + 1) + "");
            }

            //根据服务器返回的数据给创建的四个空学生进行复制,通过服务器返回的Role属性来判断
            for (int j = 0; j < teamStudents.size(); j++) {
                for (int k = 0; k < studentInfos.size(); k++) {
                    if (teamStudents.get(j).getRole().equals(studentInfos.get(k).getRole())) {
                        //赋值头像
                        studentInfos.get(k).setIcon(teamStudents.get(j).getIcon());
                        //赋值名称
                        studentInfos.get(k).setName(teamStudents.get(j).getName());
                        //赋值id,用于删除学生的时候传入服务器
                        studentInfos.get(k).setId(teamStudents.get(j).getId());
                        //电话
                        studentInfos.get(k).setTel(teamStudents.get(j).getTel());
                        //teamnum
                        studentInfos.get(k).setTeamnum(teamStudents.get(j).getTeamnum());
                        //昵称
                        studentInfos.get(k).setNickname(teamStudents.get(j).getNickname());
                        //年级
                        studentInfos.get(k).setGrade(teamStudents.get(j).getGrade());
                        //账号
                        studentInfos.get(k).setC(teamStudents.get(j).getC());
                        //性别
                        studentInfos.get(k).setGender(teamStudents.get(j).getGender());
                        //生日
                        studentInfos.get(k).setBirthday(teamStudents.get(j).getBirthday());
                        //地址
                        studentInfos.get(k).setAddress(teamStudents.get(j).getAddress());
                        //缴费状态
                        studentInfos.get(k).setPayment(teamStudents.get(j).getPayment());
                        //exp
                        studentInfos.get(k).setExp(teamStudents.get(j).getExp());
                        //money
                        studentInfos.get(k).setMoney(teamStudents.get(j).getMoney());
                        //school
                        studentInfos.get(k).setSchool(teamStudents.get(j).getSchool());
                        //favorite
                        studentInfos.get(k).setFavorite(teamStudents.get(j).getFavorite());
                        //user_type
                        studentInfos.get(k).setUser_type(teamStudents.get(j).getUser_type());
                        //status
                        studentInfos.get(k).setStatus(teamStudents.get(j).getStatus());
                    }
                }
            }

        } else {
            //创建四个默认空的小组成员
            for (int i = 0; i < 4; i++) {
                StudentInfo info = new StudentInfo();
                info.setClassnum(item.getClassnum());
                info.setTeamnum(item.getTeamnum());
                info.setRole((i + 1) + "");
                studentInfos.add(info);
            }
        }

        TeamGvAdapter teamGvAdapter = new TeamGvAdapter(activity, context, studentInfos, R.layout.teacher_gv_student);
        mGv.setAdapter(teamGvAdapter);

        //长按事件的操作学生显示该位置的删除按钮
//        mGv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long l) {
//                StudentInfo info = studentInfos.get(pos);
//                if (TextUtils.isEmpty(info.getName())) {
//                    //该位置没有学生时不响应长按事件
//                    return false;
//                } else {
//
//                    info.setShowDelete(true);
//
//                    teamGvAdapter.notifyDataSetChanged();
//
//                    PopUpManager.showPop(context, R.layout.teacher_pop_clean_cach, 0.3f, activity, new PopUpManager.onGetViewListener() {
//                        @Override
//                        public void getChildView(View view, int layoutResId) {
//                            ImageView ivClose = view.findViewById(R.id.lv_close);
//                            //文本提示信息
//                            TextView tvMsg = view.findViewById(R.id.tv_message);
//                            tvMsg.setText("确定移除该学生吗?");
//                            Button btCommit = view.findViewById(R.id.bt_commit);
//                            ivClose.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View view) {
//                                    //关闭弹框
//                                    PopUpManager.dismiss();
//                                    //状态
//                                    info.setShowDelete(false);
//                                    notifyDataSetChanged();
//                                }
//                            });
//                            btCommit.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View view) {
//                                    //请求服务器删除该位置的学生
//                                    httpDeleteSudent(info);
//                                }
//                            });
//                        }
//                    }, new PopUpManager.onDismissListener() {
//                        @Override
//                        public void onDismiss() {
//                            //消失的监听
//                            if (info.isShowDelete() != false) {
//                                info.setShowDelete(false);
//                                notifyDataSetChanged();
//                            }
//                        }
//                    });
//                    return true;
//                }
//            }
//        });
        teamGvAdapter.setOnOutLongClickListener(new TeamGvAdapter.OnOutLongClickListener() {
            @Override
            public void onLongClick(int pos, StudentInfo info) {

                info.setShowDelete(true);

                teamGvAdapter.notifyDataSetChanged();

                PopUpManager.showPop(context, R.layout.teacher_pop_clean_cach, 0.3f, activity, new PopUpManager.onGetViewListener() {
                    @Override
                    public void getChildView(View view, int layoutResId) {
                        ImageView ivClose = view.findViewById(R.id.lv_close);
                        //文本提示信息
                        TextView tvMsg = view.findViewById(R.id.tv_message);
                        tvMsg.setText("确定移除该学生吗?");
                        Button btCommit = view.findViewById(R.id.bt_commit);
                        ivClose.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //关闭弹框
                                PopUpManager.dismiss();
                                //状态
                                info.setShowDelete(false);
                                notifyDataSetChanged();
                            }
                        });
                        btCommit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //请求服务器删除该位置的学生
                                httpDeleteSudent(info);
                            }
                        });
                    }
                }, new PopUpManager.onDismissListener() {
                    @Override
                    public void onDismiss() {
                        //消失的监听
                        if (info.isShowDelete() != false) {
                            info.setShowDelete(false);
                            notifyDataSetChanged();
                        }
                    }
                });
            }
        });

        //点击事件的操作
//        mGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
//                StudentInfo info = studentInfos.get(pos);
//
//                //根据当前位置的学生是否学生,如果有学生
//                if (TextUtils.isEmpty(info.getName())) {
//                    //判断标准根据当前位置的学生姓名来判断,无学生,弹出右边的展示未分组的学生列表面板
//                    showNoTeamPop(info, teamGvAdapter);
//                } else {
//                    //有学生,跳转到添加学生界面
//                    Intent intent = new Intent(context, TeacherAddStudentActivity.class);
//                    intent.putExtra("studentinfo", info);
//
//                    context.startActivity(intent);
//                }
//            }
//        });
        teamGvAdapter.setOnOutClickListener(new TeamGvAdapter.OnOutClickListener() {
            @Override
            public void onOUtclick(int pos, StudentInfo info) {
                //根据当前位置的学生是否学生,如果有学生
                if (TextUtils.isEmpty(info.getName())) {
                    //判断标准根据当前位置的学生姓名来判断,无学生,弹出右边的展示未分组的学生列表面板
                    showNoTeamPop(info, teamGvAdapter);
                } else {
                    //有学生,跳转到添加学生界面
                    Intent intent = new Intent(context, TeacherAddStudentActivity.class);
                    intent.putExtra("studentinfo", info);

                    context.startActivity(intent);
                }
            }
        });

    }


    /**
     * 展示未分组的学生面板
     */
    private void showNoTeamPop(StudentInfo info, TeamGvAdapter teamGvAdapter) {

        view = View.inflate(context, R.layout.teacher_noteam_student, null);

        //加载视图
        rlLoading = view.findViewById(R.id.rl_loading);
        rlLoading.setVisibility(View.VISIBLE);

        //添加新学生的按钮
        btAddNewStudent = view.findViewById(R.id.bt_add_new_student);
        btAddNewStudent.setVisibility(View.GONE);
        btAddNewStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击事件,跳转到添加新学生的界面
                UiUtils.startActivity(context, TeacherAddStudentActivity.class);
                //关闭弹框
                if (window != null && window.isShowing()) {
                    window.dismiss();
                    window = null;
                    view = null;
                }
            }
        });
        //展示学生列表的数据
        lv = view.findViewById(R.id.lv);
        noTeamDatas = new ArrayList<>();
        lvAdapter = new StudentLvAdapter(context, noTeamDatas, R.layout.teacher_lv_student);
        lv.setAdapter(lvAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int currpos, long l) {
                //同步展示未分组学生的列表状态
                AddStudentToTeam(currpos, info);
            }
        });

        //设置ListView的数据
        window = new PopupWindow(view, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.MATCH_PARENT);
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        UiUtils.backgroundAlpha(activity, 0.8f);
        window.setAnimationStyle(R.style.AnimationRightFade);
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                UiUtils.backgroundAlpha(activity, 1.0f);
            }
        });

        window.showAtLocation(activity.getLayoutInflater().inflate(R.layout.teacher_activity_student_file, null), Gravity.RIGHT, 0, 0);

        //请求未分组的学生信息
        Map<String, String> map = new HashMap<>();
        map.put("type", "15");
        map.put("c", AccountUtils.getAccount(context));
        map.put("user_type", AccountUtils.getUserType(context));
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.NOTEAM, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                NoTeamClassInfo info = null;
                if (!TextUtils.isEmpty(response)) {
                    if (null != rlLoading) {
                        rlLoading.setVisibility(View.GONE);
                    }
                    try {
                        info = GsonUtil.jsonToBean(response, NoTeamClassInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("1".equals(info.getStatus())) {
                            //返回成功
                            List<StudentInfo> studentInfos = info.getList();
                            if (null != studentInfos && studentInfos.size() != 0) {
                                //通知适配器更新数据
                                noTeamDatas.addAll(studentInfos);
                                lvAdapter.notifyDataSetChanged();
                            }
                        } else {
                            //返回异常
                            UiUtils.Toast("服务器返回异常,异常码是:" + info.getStatus(), false);
                            Log.i("test", "服务器返回异常,异常码是:" + info.getStatus());
                        }
                    }
                }
            }
        });

    }


    /**
     * 请求服务器添加进学生进小组
     *
     * @param currpos    添加的学生
     * @param studentAdd 被添加的位置的学生对象
     */
    private void AddStudentToTeam(int currpos, StudentInfo studentAdd) {
        CustomDialogManager.show(context, "添加中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "12");
        map.put("c", AccountUtils.getAccount(context));
        map.put("id", noTeamDatas.get(currpos).getId());
        map.put("classnum", studentAdd.getClassnum());
        map.put("teamnum", studentAdd.getTeamnum());
        map.put("role", studentAdd.getRole());
        map.put("platform", "8");


        HttpUtils.post(HttpAdress.ADDSTUDENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
                CustomDialogManager.dissmiss();
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    CommitResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, CommitResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("1".equals(info.status)) {
                            //返回成功

                            //同步展示未分组学生的列表状态
                            noTeamDatas.remove(currpos);
                            lvAdapter.notifyDataSetChanged();

                            BusInfo busInfo = new BusInfo();
                            busInfo.setType(UPDATAPAGEDATA);
                            EventBus.getDefault().post(busInfo);

                            //关闭右侧弹框
                            if (window != null && window.isShowing()) {
                                window.dismiss();
                                window = null;
                                view = null;
                            }
                        } else {
                            UiUtils.Toast("添加失败,返回错误码:" + info.status, false);
                            Log.i("test", "返回器返回异常,错误码是:" + info.status);
                        }
                    }
                } else {
                    Log.i("test", "服务返回数据异常");
                }
            }
        });


    }


    /**
     * 请求服务器删除该位置学生的方法
     *
     * @param item
     */
    private void httpDeleteSudent(StudentInfo item) {

        PopUpManager.dismiss();

        CustomDialogManager.show(context, "移除中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "13");
        map.put("c", AccountUtils.getAccount(context));
        map.put("id", item.getId() + "");
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.MOVESTUDENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
                CustomDialogManager.dissmiss();
                if (item.isShowDelete() != false) {
                    item.setShowDelete(false);
                    notifyDataSetChanged();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    CommitResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, CommitResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("1".equals(info.status)) {
                            //返回成功
                            UiUtils.Toast("移除成功", false);
                            //通知页面刷新
                            BusInfo busInfo = new BusInfo();
                            busInfo.setType(UPDATAPAGEDATA);
                            EventBus.getDefault().post(busInfo);
                        } else {
                            UiUtils.Toast("移除失败,返回错误码:" + info.status, false);
                            Log.i("test", "返回器返回异常,错误码是:" + info.status);
                        }
                    }
                } else {
                    Log.i("test", "服务返回数据异常");
                }
            }
        });
    }

}
